<script src="https://cdn.jsdelivr.net/npm/marked@12.0.2/marked.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.6/dist/purify.min.js" crossorigin="anonymous"></script>
<script>
    (function () {
        const form = document.getElementById("llm-form");
        const conversationIdDisplay = document.getElementById("conversation-id-display");
        const feedback = document.getElementById("llm-feedback");
        const conversation = document.getElementById("conversation");
        const messagesContainer = document.getElementById("messages-container");
        const submitText = document.getElementById("submit-text");
        const submitLoading = document.getElementById("submit-loading");
        const textarea = document.getElementById("id_question");
        const clearButton = document.getElementById("clear-input");
        const refreshButton = document.getElementById("refresh-messages");
        const conversationStatus = document.getElementById("conversation-status");
        const messageCount = document.getElementById("message-count");
        const loadingIndicator = document.getElementById("loading-indicator");
        const loadMoreButton = document.getElementById("load-more-messages");
        const newConversationButton = document.getElementById("start-new-conversation");
        const submitButton = form ? form.querySelector('button[type="submit"]') : null;
        
        let isSubmitting = false;
        let csrfToken = "";
        let currentConversationId = "{{ mistake.llm_conversation_id }}";
        const senderLabels = {
            student: "👤 学生",
            teacher: "👨‍🏫 老师",
            llm: "🤖 智能助教"
        };
        const viewerIsTeacher = {{ user.is_teacher|yesno:"true,false" }};
        const currentMistakeId = Number({{ mistake.id }});

        function getCookieValue(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) {
                return parts.pop().split(";").shift();
            }
            return "";
        }

        function ensureCsrfToken() {
            if (csrfToken) {
                return csrfToken;
            }
            csrfToken = getCookieValue("csrftoken") || "";
            return csrfToken;
        }

        ensureCsrfToken();

        function formatConversationId(conversationId) {
            if (!conversationId) {
                return "--------";
            }
            return conversationId.length > 8
                ? `${conversationId.substring(0, 8)}...`
                : conversationId;
        }

        if (conversationIdDisplay) {
            const storedId =
                conversationIdDisplay.dataset.fullId ||
                currentConversationId ||
                "";
            conversationIdDisplay.dataset.fullId = storedId;
            conversationIdDisplay.textContent = formatConversationId(storedId);
        }

        if (window.marked && typeof window.marked.setOptions === "function") {
            window.marked.setOptions({ breaks: true, gfm: true });
        }

        function escapeHtml(str) {
            if (!str) return "";
            return str.replace(/[&<>"']/g, (char) => {
                switch (char) {
                    case "&":
                        return "&amp;";
                    case "<":
                        return "&lt;";
                    case ">":
                        return "&gt;";
                    case '"':
                        return "&quot;";
                    case "'":
                        return "&#39;";
                    default:
                        return char;
                }
            });
        }

        function renderMarkdownContent(raw) {
            const text = typeof raw === "string" ? raw : "";
            let html;

            if (window.marked && typeof window.marked.parse === "function") {
                html = window.marked.parse(text);
            } else {
                html = escapeHtml(text).replace(/\n/g, "<br>");
            }

            if (window.DOMPurify && typeof window.DOMPurify.sanitize === "function") {
                return window.DOMPurify.sanitize(html);
            }

            return html;
        }

        function typesetMath(element, attempt = 0) {
            if (!element) return;
            if (window.MathJax && typeof window.MathJax.typesetPromise === "function") {
                window.MathJax.typesetPromise([element]).catch((error) => {
                    console.error("MathJax typeset failed:", error);
                });
            } else if (attempt < 5) {
                setTimeout(() => typesetMath(element, attempt + 1), 300);
            }
        }

        function renderElementContent(element, raw) {
            if (!element) return;
            const source = typeof raw === "string" ? raw : element.dataset.raw || "";
            element.dataset.raw = source;
            element.innerHTML = renderMarkdownContent(source);
            typesetMath(element);
        }

        function buildMessageElement({ sender, content, timestamp, messageId }) {
            const messageDiv = document.createElement("div");
            messageDiv.className = `chat-entry ${sender}`;

            if (messageId) {
                messageDiv.dataset.messageId = messageId;
            }

            const senderLabel = senderLabels[sender] || senderLabels.llm;

            const strong = document.createElement("strong");
            strong.textContent = senderLabel;

            const timeEl = document.createElement("small");
            timeEl.textContent = timestamp;

            const contentDiv = document.createElement("div");
            contentDiv.className = "message-content";
            contentDiv.dataset.raw = typeof content === "string" ? content : "";

            messageDiv.appendChild(strong);
            messageDiv.appendChild(timeEl);
            messageDiv.appendChild(contentDiv);

            renderElementContent(contentDiv, content);

            return messageDiv;
        }

        function renderEmptyState() {
            if (!messagesContainer) return;
            messagesContainer.innerHTML = `
                <div style="text-align:center;padding:3rem 2rem;" id="empty-state">
                    <div style="font-size:3rem;margin-bottom:1rem;opacity:0.3;">💬</div>
                    <p style="margin:0;color:var(--text-secondary);">
                        还没有对话记录，向智能助教提问吧！
                    </p>
                </div>
            `;
        }

        function resetConversationUI() {
            if (!messagesContainer) return;
            renderEmptyState();
            updateMessageCount();
            if (loadMoreButton) {
                loadMoreButton.style.display = "none";
            }
            scrollToBottom();
        }

        if (messagesContainer) {
            messagesContainer.querySelectorAll(".message-content").forEach((element) => {
                renderElementContent(element);
            });
        }

        function scrollToBottom() {
            if (conversation) {
                setTimeout(() => {
                    conversation.scrollTop = conversation.scrollHeight;
                }, 100);
            }
        }

        scrollToBottom();
        updateMessageCount();

        function updateMessageCount() {
            if (!messagesContainer) {
                return;
            }
            const messages = messagesContainer.querySelectorAll('.chat-entry');
            if (messageCount) {
                const countText = messageCount.querySelector('strong');
                if (countText) {
                    countText.textContent = messages.length;
                }
            }
        }

        function showFeedback(message, type = 'info') {
            if (!feedback) {
                const logger = type === 'error' ? console.error : console.log;
                logger.call(console, message);
                return;
            }
            feedback.style.display = "block";
            feedback.className = `message message-${type}`;
            feedback.textContent = message;
        }

        function hideFeedback(delay = 3000) {
            if (!feedback) {
                return;
            }
            setTimeout(() => {
                feedback.style.display = "none";
            }, delay);
        }

        if (form) {
            const csrfTokenInput = form.querySelector('input[name="csrfmiddlewaretoken"]');
            csrfToken = csrfTokenInput ? csrfTokenInput.value : ensureCsrfToken();

            function setSubmitting(submitting) {
                isSubmitting = submitting;
                if (submitButton) {
                    submitButton.disabled = submitting;
                    submitButton.style.opacity = submitting ? "0.7" : "1";
                }
                if (textarea) {
                    textarea.disabled = submitting;
                }
                if (submitText) {
                    submitText.style.display = submitting ? "none" : "inline";
                }
                if (submitLoading) {
                    submitLoading.style.display = submitting ? "inline-flex" : "none";
                }
            }

            if (newConversationButton) {
                newConversationButton.addEventListener("click", async () => {
                    if (!csrfToken) {
                        showFeedback("无法获取安全令牌，请刷新页面后重试", "error");
                        return;
                    }

                    newConversationButton.disabled = true;
                    const originalText = newConversationButton.textContent;
                    newConversationButton.textContent = "⏳ 创建中...";

                    try {
                        const response = await fetch(
                            "{% url 'learning:mistake_new_llm_conversation' mistake.pk %}",
                            {
                                method: "POST",
                                headers: {
                                    "X-Requested-With": "XMLHttpRequest",
                                    "X-CSRFToken": csrfToken,
                                },
                            }
                        );

                        let data = {};
                        try {
                            data = await response.json();
                        } catch (parseError) {
                            throw new Error("解析服务器响应失败");
                        }

                        if (!response.ok) {
                            const errorMessage =
                                data.error ||
                                data.message ||
                                `请求失败 (${response.status})`;
                            showFeedback("❌ " + errorMessage, "error");
                            return;
                        }

                        const newConversationId = data.conversation_id || "";
                        currentConversationId = newConversationId;

                        if (conversationStatus) {
                            if (newConversationId) {
                                conversationStatus.className = "pill success";
                                conversationStatus.innerHTML = "🟢 会话进行中";
                            } else {
                                conversationStatus.className = "pill";
                                conversationStatus.innerHTML = "⚪ 未开始会话";
                            }
                        }

                        if (conversationIdDisplay) {
                            conversationIdDisplay.dataset.fullId = newConversationId;
                            conversationIdDisplay.textContent = formatConversationId(
                                newConversationId
                            );
                        }

                        resetConversationUI();
                        const successMessage =
                            data.message || "🆕 已创建新的助教会话";
                        showFeedback(successMessage, "success");
                        hideFeedback(2000);
                    } catch (error) {
                        showFeedback("❌ 创建会话失败：" + error.message, "error");
                    } finally {
                        newConversationButton.disabled = false;
                        newConversationButton.textContent = originalText;
                    }
                });
            }

            form.addEventListener("submit", async (event) => {
                event.preventDefault();
                
                if (isSubmitting) return;
                
                const questionText = textarea.value.trim();
                
                if (!questionText) {
                    showFeedback("请输入您的问题", "error");
                    if (textarea) {
                        textarea.focus();
                    }
                    return;
                }
                
                setSubmitting(true);
                showFeedback("🔄 正在向智能助教提问，请稍候...", "info");

                try {
                    const formData = new FormData(form);
                    
                    if (!formData.has('question') || !formData.get('question').trim()) {
                        formData.set('question', questionText);
                    }
                    
                    console.log("Form data entries:");
                    for (let pair of formData.entries()) {
                        console.log(pair[0] + ': ' + pair[1]);
                    }
                    
                    const response = await fetch(form.action, {
                        method: "POST",
                        headers: {"X-Requested-With": "XMLHttpRequest"},
                        body: formData
                    });

                    const data = await response.json();

                    if (!response.ok) {
                        const errorMessage =
                            data.errors?.question?.join("；") ||
                            data.errors?.__all__?.join("；") ||
                            `请求失败 (${response.status})`;
                        showFeedback("❌ " + errorMessage, "error");
                        return;
                    }

                    if (data.conversation_id && data.conversation_id !== currentConversationId) {
                        currentConversationId = data.conversation_id;
                        
                        if (conversationStatus) {
                            conversationStatus.className = "pill success";
                            conversationStatus.innerHTML = "🟢 会话进行中";
                        }

                        if (conversationIdDisplay) {
                            conversationIdDisplay.dataset.fullId = currentConversationId;
                            conversationIdDisplay.textContent = formatConversationId(
                                currentConversationId
                            );
                        }
                    }

                    addMessage(questionText, "student");
                    
                    if (data.answer) {
                        addMessage(data.answer, "llm");
                        showFeedback("✅ 智能助教已回复", "success");
                    } else {
                        showFeedback("⚠️ 收到空回复", "warning");
                    }
                    
                    form.reset();
                    if (textarea) {
                        textarea.focus();
                    }
                    
                    hideFeedback();
                } catch (error) {
                    showFeedback("❌ 网络错误：" + error.message, "error");
                } finally {
                    setSubmitting(false);
                }
            });

            if (clearButton && textarea) {
                clearButton.addEventListener("click", () => {
                    textarea.value = "";
                    textarea.focus();
                });
            }

            document.querySelectorAll(".quick-question").forEach(button => {
                button.addEventListener("click", () => {
                    if (!textarea) {
                        return;
                    }
                    const question = button.dataset.question;
                    textarea.value = question;
                    textarea.focus();
                });
            });

            if (textarea) {
                textarea.addEventListener("keydown", (event) => {
                    if (event.ctrlKey && event.key === "Enter") {
                        event.preventDefault();
                        form.dispatchEvent(new Event('submit'));
                    }
                });

                textarea.addEventListener("input", () => {
                    textarea.style.height = "auto";
                    textarea.style.height = textarea.scrollHeight + "px";
                });

                const hint = document.createElement("div");
                hint.style.cssText = "font-size:0.75rem;color:var(--text-tertiary);margin-top:0.5rem;text-align:center;";
                hint.textContent = "💡 提示：使用 Ctrl+Enter 快速发送";
                if (textarea.parentElement) {
                    textarea.parentElement.appendChild(hint);
                }
            }
        }

        function addMessage(content, sender, timestamp, messageId) {
            const emptyStateElement = document.getElementById("empty-state");
            if (emptyStateElement && emptyStateElement.parentNode) {
                emptyStateElement.remove();
            }

            const timeStr = timestamp || new Date().toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });

            const messageBlock = buildMessageElement({
                sender,
                content: typeof content === "string" ? content : "",
                timestamp: timeStr,
                messageId
            });

            messagesContainer.appendChild(messageBlock);
            updateMessageCount();
            scrollToBottom();
        }

        async function fetchMessages(lastId = "") {
            if (!currentConversationId) {
                return { messages: [], has_more: false };
            }
            
            const url = new URL("{% url 'learning:mistake_get_messages' mistake.pk %}", window.location.origin);
            if (lastId) {
                url.searchParams.set("last_id", lastId);
            }
            url.searchParams.set("limit", "20");
            
            const response = await fetch(url, {
                method: "GET",
                headers: { "X-Requested-With": "XMLHttpRequest" }
            });
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}`);
            }
            
            return await response.json();
        }

        if (refreshButton) {
            refreshButton.addEventListener("click", async () => {
                if (!currentConversationId) {
                    showFeedback("当前没有活跃的会话", "info");
                    hideFeedback(2000);
                    return;
                }
                
                refreshButton.disabled = true;
                const originalText = refreshButton.innerHTML;
                refreshButton.innerHTML = "⏳ 刷新中...";
                
                try {
                    const data = await fetchMessages();
                    
                    if (data.messages && data.messages.length > 0) {
                        const wasAtBottom = conversation.scrollHeight - conversation.scrollTop === conversation.clientHeight;
                        
                        messagesContainer.innerHTML = "";
                        
                        data.messages.forEach(msg => {
                            let timeStr;
                            if (msg.created_at) {
                                const date = new Date(msg.created_at);
                                timeStr = date.toLocaleString('zh-CN', {
                                    year: 'numeric',
                                    month: '2-digit',
                                    day: '2-digit',
                                    hour: '2-digit',
                                    minute: '2-digit',
                                    second: '2-digit'
                                });
                            } else {
                                timeStr = new Date().toLocaleString('zh-CN');
                            }

                            const messageDiv = buildMessageElement({
                                sender: msg.sender,
                                content: typeof msg.content === "string" ? msg.content : "",
                                timestamp: timeStr,
                                messageId: msg.id
                            });

                            messagesContainer.appendChild(messageDiv);
                        });
                        
                        updateMessageCount();
                        
                        if (wasAtBottom) {
                            scrollToBottom();
                        }
                        
                        showFeedback("✅ 消息已刷新", "success");
                        hideFeedback(2000);
                    } else {
                        resetConversationUI();
                        showFeedback("暂无消息", "info");
                        hideFeedback(2000);
                    }
                } catch (error) {
                    showFeedback("刷新失败：" + error.message, "error");
                } finally {
                    refreshButton.disabled = false;
                    refreshButton.innerHTML = originalText;
                }
            });
        }
        
        if (loadMoreButton) {
            loadMoreButton.addEventListener("click", async () => {
                const firstMessage = messagesContainer.querySelector(".chat-entry");
                const lastId = firstMessage?.dataset.messageId || "";
                
                loadMoreButton.disabled = true;
                const originalText = loadMoreButton.textContent;
                loadMoreButton.textContent = "⏳ 加载中...";
                
                try {
                    const data = await fetchMessages(lastId);
                    
                    if (data.messages && data.messages.length > 0) {
                        const fragment = document.createDocumentFragment();
                        
                        data.messages.reverse().forEach(msg => {
                            let timeStr;
                            if (msg.created_at) {
                                timeStr = new Date(msg.created_at).toLocaleString('zh-CN');
                            } else {
                                timeStr = new Date().toLocaleString('zh-CN');
                            }
                            
                            if (msg.query) {
                                const questionDiv = buildMessageElement({
                                    sender: "student",
                                    content: msg.query,
                                    timestamp: timeStr,
                                    messageId: msg.id
                                });
                                fragment.appendChild(questionDiv);
                            }
                            
                            if (msg.answer) {
                                const answerDiv = buildMessageElement({
                                    sender: "llm",
                                    content: msg.answer,
                                    timestamp: timeStr,
                                    messageId: msg.id
                                });
                                fragment.appendChild(answerDiv);
                            }
                        });
                        
                        messagesContainer.insertBefore(fragment, messagesContainer.firstChild);
                        updateMessageCount();
                        
                        if (!data.has_more) {
                            loadMoreButton.style.display = "none";
                        }
                        
                        showFeedback("✅ 已加载更多消息", "success");
                        hideFeedback(2000);
                    } else {
                        loadMoreButton.style.display = "none";
                        showFeedback("没有更多消息了", "info");
                        hideFeedback(2000);
                    }
                } catch (error) {
                    showFeedback("加载失败：" + error.message, "error");
                } finally {
                    loadMoreButton.disabled = false;
                    loadMoreButton.textContent = originalText;
                }
            });
        }

        const showConversationsBtn = document.getElementById("show-conversations");
        const conversationsModal = document.getElementById("conversations-modal");
        const closeModalBtn = document.getElementById("close-conversations-modal");
        const conversationsList = document.getElementById("conversations-list");

        const conversationListUrl = new URL("{% url 'learning:conversation_list' %}", window.location.origin);
        {% if user.is_teacher and mistake.student.assigned_teacher_id == user.id %}
        conversationListUrl.searchParams.set("student", "{{ mistake.student_id }}");
        {% endif %}

        async function fetchConversations() {
            try {
                const response = await fetch(conversationListUrl.toString(), {
                    method: "GET",
                    headers: { "X-Requested-With": "XMLHttpRequest" }
                });
                
                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new Error(errorData.error || `HTTP ${response.status}`);
                }
                
                return await response.json();
            } catch (error) {
                console.error("Failed to fetch conversations:", error);
                throw error;
            }
        }

        async function activateConversation(conversationId, options = {}) {
            if (!conversationId) {
                return;
            }

            const token = ensureCsrfToken();
            if (!token) {
                showFeedback("无法获取安全令牌，请刷新页面后重试", "error");
                return;
            }

            const payload = {
                conversation_id: conversationId,
            };

            if (options.conversationName) {
                payload.name = options.conversationName;
            }

            try {
                if (loadingIndicator) {
                    loadingIndicator.style.display = "block";
                }

                const response = await fetch(
                    "{% url 'learning:mistake_switch_llm_conversation' mistake.pk %}",
                    {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                            "X-Requested-With": "XMLHttpRequest",
                            "X-CSRFToken": token,
                        },
                        credentials: "same-origin",
                        body: JSON.stringify(payload),
                    }
                );

                let data = {};
                try {
                    data = await response.json();
                } catch (parseError) {
                    data = {};
                }

                if (!response.ok) {
                    const message =
                        data.error ||
                        data.message ||
                        `切换失败 (${response.status})`;
                    showFeedback("❌ " + message, "error");
                    return;
                }

                currentConversationId = data.conversation_id || conversationId;

                if (conversationStatus) {
                    conversationStatus.className = "pill success";
                    conversationStatus.innerHTML = "🟢 会话进行中";
                }

                if (conversationIdDisplay) {
                    conversationIdDisplay.dataset.fullId = currentConversationId;
                    conversationIdDisplay.textContent = formatConversationId(
                        currentConversationId
                    );
                }

                closeConversationsModal();
                showFeedback(data.message || "✅ 已切换会话", "success");
                hideFeedback(1500);

                setTimeout(() => {
                    window.location.reload();
                }, 200);
            } catch (error) {
                showFeedback("切换失败：" + error.message, "error");
            } finally {
                if (loadingIndicator) {
                    loadingIndicator.style.display = "none";
                }
            }
        }

        async function showConversationsList() {
            conversationsModal.style.display = "block";
            document.body.style.overflow = "hidden";
            
            conversationsList.innerHTML = `
                <div style="text-align:center;padding:2rem;color:var(--text-secondary);">
                    <div class="spinner" style="margin:0 auto 1rem;"></div>
                    <p>加载中...</p>
                </div>
            `;
            
            try {
                const data = await fetchConversations();
                
                if (data.conversations && data.conversations.length > 0) {
                    conversationsList.innerHTML = "";
                    
                    data.conversations.forEach(conv => {
                        const convCard = document.createElement("div");
                        convCard.style.cssText = "background:var(--surface);border:1px solid var(--border-subtle);border-radius:var(--radius-md);padding:1rem;transition:all var(--transition-base);cursor:pointer;";
                        
                        const createdAt = conv.created_at
                            ? new Date(conv.created_at * 1000).toLocaleString('zh-CN')
                            : "时间未知";
                        const isActive = conv.id === currentConversationId;
                        const belongsToCurrentMistake = !!(conv.mistake && Number(conv.mistake.id) === currentMistakeId);
                        
                        convCard.innerHTML = `
                            <div style="display:flex;align-items:start;justify-content:space-between;gap:1rem;">
                                <div style="flex:1;">
                                    <div style="display:flex;align-items:center;gap:0.5rem;margin-bottom:0.5rem;">
                                        <h4 style="margin:0;font-size:1rem;">${conv.name || '未命名会话'}</h4>
                                        ${isActive ? '<span class="pill success">✓ 当前会话</span>' : ''}
                                        ${(!conv.is_active_local || conv.status === 'archived') ? '<span class="pill">历史记录</span>' : ''}
                                    </div>
                                    ${viewerIsTeacher && conv.student && conv.student.username ? `
                                        <p style="margin:0;font-size:0.875rem;color:var(--text-secondary);">
                                            👤 学生: <strong>${conv.student.username}</strong>
                                        </p>
                                    ` : ''}
                                    ${conv.mistake ? `
                                        <p style="margin:0.5rem 0;font-size:0.875rem;color:var(--text-secondary);">
                                            📝 关联错题: <strong>${conv.mistake.title}</strong>
                                            <span class="pill" style="margin-left:0.5rem;">${conv.mistake.status}</span>
                                        </p>
                                    ` : `
                                        <p style="margin:0.5rem 0;font-size:0.875rem;color:var(--text-tertiary);font-style:italic;">
                                            ⚠️ 未关联错题
                                        </p>
                                    `}
                                    <p style="margin:0.5rem 0 0 0;font-size:0.8125rem;color:var(--text-tertiary);">
                                        🕐 创建于 ${createdAt}
                                    </p>
                                    <p style="margin:0.25rem 0 0 0;font-size:0.8125rem;color:var(--text-tertiary);">
                                        🆔 ${conv.id.substring(0, 8)}...
                                    </p>
                                </div>
                                <div style="display:flex;flex-direction:column;gap:0.5rem;">
                                    ${conv.mistake ? `
                                        <button class="button small" data-action="goto" style="white-space:nowrap;">
                                            查看错题
                                        </button>
                                    ` : ''}
                                    ${!isActive && belongsToCurrentMistake ? `
                                        <button class="button small secondary" data-action="switch" style="white-space:nowrap;">
                                            切换到此会话
                                        </button>
                                    ` : ''}
                                </div>
                            </div>
                        `;
                        
                        convCard.addEventListener("mouseenter", () => {
                            if (!isActive) {
                                convCard.style.borderColor = "var(--accent)";
                                convCard.style.boxShadow = "var(--shadow-md)";
                            }
                        });
                        
                        convCard.addEventListener("mouseleave", () => {
                            convCard.style.borderColor = isActive ? "var(--accent)" : "var(--border-subtle)";
                            convCard.style.boxShadow = isActive ? "var(--shadow-sm)" : "none";
                        });
                        
                        if (isActive) {
                            convCard.style.borderColor = "var(--accent)";
                            convCard.style.background = "var(--accent-soft)";
                            convCard.style.boxShadow = "var(--shadow-sm)";
                        }
                        
                        convCard.addEventListener("click", (e) => {
                            const target = e.target;
                            const conversationName = conv.name || "";
                            
                            if (target.tagName === 'BUTTON') {
                                e.stopPropagation();
                                const action = target.dataset.action;
                                
                                if (action === 'goto' && conv.mistake) {
                                    window.location.href = conv.mistake.url;
                                } else if (action === 'switch' && conv.mistake) {
                                    if (belongsToCurrentMistake) {
                                        activateConversation(conv.id, { conversationName });
                                    } else {
                                        window.location.href = conv.mistake.url;
                                    }
                                }
                                return;
                            }
                            
                            if (belongsToCurrentMistake) {
                                if (!isActive) {
                                    activateConversation(conv.id, { conversationName });
                                } else {
                                    closeConversationsModal();
                                }
                            } else if (conv.mistake) {
                                window.location.href = conv.mistake.url;
                            } else {
                                showFeedback("此会话未关联错题，无法切换", "warning");
                                hideFeedback(2000);
                            }
                        });
                        
                        conversationsList.appendChild(convCard);
                    });
                    
                    if (data.has_more) {
                        const loadMoreDiv = document.createElement("div");
                        loadMoreDiv.style.cssText = "text-align:center;padding:1rem;";
                        loadMoreDiv.innerHTML = `
                            <button class="button secondary">加载更多会话</button>
                        `;
                        conversationsList.appendChild(loadMoreDiv);
                    }
                } else {
                    conversationsList.innerHTML = `
                        <div style="text-align:center;padding:3rem;color:var(--text-secondary);">
                            <div style="font-size:3rem;margin-bottom:1rem;opacity:0.3;">💬</div>
                            <p>还没有会话记录</p>
                        </div>
                    `;
                }
            } catch (error) {
                console.error("Error loading conversations:", error);
                conversationsList.innerHTML = `
                    <div style="text-align:center;padding:2rem;">
                        <div style="font-size:3rem;margin-bottom:1rem;opacity:0.3;">❌</div>
                        <p style="color:var(--error);margin-bottom:1rem;">加载失败：${error.message}</p>
                        <button class="button secondary" id="retry-load-conversations">重试</button>
                    </div>
                `;
                
                const retryBtn = document.getElementById("retry-load-conversations");
                if (retryBtn) {
                    retryBtn.addEventListener("click", showConversationsList);
                }
            }
        }

        function closeConversationsModal() {
            conversationsModal.style.display = "none";
            document.body.style.overflow = "auto";
        }

        if (showConversationsBtn) {
            showConversationsBtn.addEventListener("click", showConversationsList);
        }

        if (closeModalBtn) {
            closeModalBtn.addEventListener("click", closeConversationsModal);
        }

        if (conversationsModal) {
            conversationsModal.addEventListener("click", (e) => {
                if (e.target === conversationsModal) {
                    closeConversationsModal();
                }
            });
        }

        document.addEventListener("keydown", (e) => {
            if (e.key === "Escape" && conversationsModal.style.display === "block") {
                closeConversationsModal();
            }
        });

    })();
</script>
